#include "njs_video_render_manager.h"
#include <ace/xcomponent/native_interface_xcomponent.h>
#include "api/video/video_render_manager.h"
#include "../rtc_log.h"

namespace ohosrtc {
NJSVideoRenderManager* NJSVideoRenderManager::GetInstance() {
  static auto inst = new NJSVideoRenderManager();
  return inst;
}

napi_value NJSVideoRenderManager::Init(napi_env env, napi_value exports) {
  // XComponent组件load时初始化render，并把XComponent组件绑定到render，监听组件的Surface生命周期事件
  napi_value exportInstance = nullptr;
  if (napi_get_named_property(env, exports, OH_NATIVE_XCOMPONENT_OBJ,
                              &exportInstance) == napi_ok) {
    OH_NativeXComponent *nativeXComponent = nullptr;
    if (napi_unwrap(env, exportInstance, reinterpret_cast<void **>(&nativeXComponent)) == napi_ok) {
      char idStr[OH_XCOMPONENT_ID_LEN_MAX + 1] = {'\0'};
      uint64_t idSize = OH_XCOMPONENT_ID_LEN_MAX + 1;
      if (OH_NativeXComponent_GetXComponentId(nativeXComponent, idStr, &idSize) == OH_NATIVEXCOMPONENT_RESULT_SUCCESS) {
        std::string id(idStr);
        RTC_LOG << "NJSVideoRenderManager CreateRender "<< id;
        auto render = webrtc::VideoRenderManager::GetInstance()->CreateRender(id);
        if (render) {
          render->AttachHandle(nativeXComponent);
        }
      }
    }
  }
  return exports;
}

NJSVideoRenderManager::NJSVideoRenderManager() {}

NJSVideoRender* NJSVideoRenderManager::GetRender(const std::string &id) {
	auto impl = webrtc::VideoRenderManager::GetInstance()->GetRender(id);
	auto render = new NJSVideoRender(impl);
  return render;
}

void NJSVideoRenderManager::DisposeRender(const std::string &id) {
  return webrtc::VideoRenderManager::GetInstance()->DisposeRender(id);
}
}